//
//  UserInfoSettingViewController.m
//  MooreDoll
//
//  Created by 郭景豪 on 2014/12/9.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "UserInfoSettingViewController.h"
#import "SelectFiedViewController.h"
#import "LoginOrRegistViewController.h"
@interface UserInfoSettingViewController ()
{
    AFHTTPRequestOperationManager *afManager;
}
@property (weak, nonatomic) UITextField *TF_ActiveField;

@end

@implementation UserInfoSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    self.title = NSLocalizedString(@"填寫個人資料", nil);
    

}
-(void)viewDidAppear:(BOOL)animated
{
    //檢查目前網路狀態
    if ([XMPPSharedInstance sharedInstance].state == 0) {
        
        //這邊註冊了登入後的 delegate
        [XMPPSharedInstance sharedInstance].stateDelegate = self;
        
        //執行登入
        [[XMPPSharedInstance sharedInstance] loginXMPP];
    }
}
- (IBAction)sendUserInfo:(id)sender {
    
    //檢查有沒有輸入密碼
    if (self.TF_Password.text.length >0) {
        
        //檢查兩組密碼是否一樣
        if ([ValidateText validatePassword:self.TF_Password.text]&&[self.TF_Password.text isEqualToString:self.TF_Affirm.text])
        {
            
            [self sendPassword:self.TF_Password.text];
            
        }else if (![ValidateText validatePassword:self.TF_Password.text]){
            
            [WinkAlertView _showAlertViewWithTitle:@"密碼格式不正確" content:@"" cancelButtonTitle:@"確認" showTime:2.0f];

        }else if (![self.TF_Password.text isEqualToString:self.TF_Affirm.text])
        {
            [WinkAlertView _showAlertViewWithTitle:@"密碼不相同" content:@"" cancelButtonTitle:@"確認" showTime:2.0f];

        }
        
    }else{
        [WinkAlertView _showAlertViewWithTitle:@"請輸入密碼" content:@"" cancelButtonTitle:@"確認" showTime:2.0f];
    }
}
-(void)sendPassword:(NSString *)password
{
    afManager = [AFHTTPRequestOperationManager manager];
    
    afManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    afManager.responseSerializer.acceptableContentTypes = [afManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    
    //取出國碼加帳號
    NSString *account = [TelephonyInfo accountAddCountryCode];

    
    NSDictionary *parameters = @{@"type":@"changepwd",@"secret":@"openfire",@"username":account,@"oldpwd":DEFAULT_PASSWORD,@"newpwd":password};
    
    NSLog(@"%@",parameters);
    
    //取得token
    [afManager POST:MD_SERVER_API parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        NSLog(@"JSON: %@", responseObject);
        
        
        NSString *responseResult = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
        
        //成功
        if ([responseResult isEqualToString:@"0"]) {
            
            //儲存密碼
            [[NSUserDefaults standardUserDefaults]setValue:password forKey:@"password"];
            NSString *userImagePath;
            if (self.photoButton.imageView.image != nil) {
                //儲存使用者的圖片
                userImagePath = [[WriteToFileImage sharedInstance]GetAndWriteToFileImage:self.photoButton.imageView.image];
            }else
            {
                //儲存使用者的圖片
                userImagePath = [[WriteToFileImage sharedInstance]GetAndWriteToFileImage:[UIImage imageNamed:@"dficon_user"]];
            }
            
            if (userImagePath != nil) {
                //將名字還有 圖片路徑包進字典
                NSDictionary *dict = @{@"userImage":userImagePath,@"userName":self.TF_Name.text};
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                   
                    while (dict == nil) {
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[XMPPSharedInstance sharedInstance]changeVCard:dict];

                    });

                });                //執行變更名字和照片
                
            }
        }else
        {
            
            [WinkAlertView _showAlertViewWithTitle:@"失敗" content:responseObject[@"msg"] cancelButtonTitle:@"確認" showTime:3.0f];
            
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        
        
        [WinkAlertView _showAlertViewWithTitle:@"失敗" content:@"網路連結失敗" cancelButtonTitle:@"確認" showTime:3.0f];
        
        
    }];

}
- (IBAction)takePhoto:(TakePhotoButton *)sender {
    
    if (sender.delegate!=self) {
        sender.delegate = self;
    }
}
#pragma mark 大頭貼 delegate
-(void)TakePhotoButtonOpenCamera:(UIImagePickerController *)camera
{
    [self presentViewController:camera animated:YES completion:nil];
}
-(void)TakePhotoButtonOpenPhotoLibrary:(UIImagePickerController *)PhotoLibrary
{
    [self presentViewController:PhotoLibrary animated:YES completion:nil];
    
}
-(void)TakePhotoAlertDismissVC
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
-(void)takePhotoClance
{
    [self dismissViewControllerAnimated:YES completion:nil];

}

#pragma mark 文字 鍵盤 delegate
- (void) keyboardWillShow:(NSNotification *)notification
{
    [CoverKeyboard scrollView:self.SV_main textField:self.TF_ActiveField notification:notification view:self.view];
}

- (void) keyboardWillBeHidden:(NSNotification *)notification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.SV_main.contentInset = contentInsets;
    self.SV_main.scrollIndicatorInsets = contentInsets;
}

//開始編輯
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.TF_ActiveField = textField;
}

//結束編輯
- (void)textFieldDidEndEditing:(UITextField *)sender
{
    self.TF_ActiveField = nil;
}

//按下return健
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField==self.TF_Name) {
        
        [self.TF_Password becomeFirstResponder];
        
    }else if(textField==self.TF_Password)
        
    {
        [self.TF_Affirm becomeFirstResponder];
    }else if(textField==self.TF_Affirm)
        
    {
        [self.TF_Affirm resignFirstResponder];
    }
    
    return YES;
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    
    if (self.V_ContentView == touch.view) {
        [self.view endEditing:YES];
    }
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark connectStateDelegate 連線的delegate
-(void)connectState:(int)state
{
    //因為這邊delegate 是在背景執行時觸發 但因為我們有做切換畫面 所以要回到主線程 不然會出問題
    dispatch_async(dispatch_get_main_queue(), ^{
        loginState = state;

        switch (state) {
            case 0:
                NSLog(@"連線中斷");
                [[[UIAlertView alloc]initWithTitle:@"注意" message:@"註冊登入失敗，請重新註冊" delegate:self cancelButtonTitle:@"確認" otherButtonTitles:nil]show];

                break;
            case 1:
                NSLog(@"進行連線");
                break;
            case 2:
                NSLog(@"連線成功");
                break;
            default:
                break;
        }
    });
    
}

-(void)getUserImageIsOK:(NSMutableDictionary *)results
{
    SelectFiedViewController *selectFiedVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SelectFiedViewController"];
    [selectFiedVC.navigationItem setHidesBackButton:YES];

    [self.navigationController pushViewController:selectFiedVC animated:YES];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        //當使用者註冊完畢 第一次登入失敗 就請他重新註冊
        [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(UIViewController *controller, NSUInteger idx, BOOL *stop) {
            if ([controller isKindOfClass:[LoginOrRegistViewController class]]) {
                
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"password"];

                [self.navigationController popToViewController:controller animated:YES];
                *stop = YES;
            }
        }];

    }
}

@end
